package com.econ.powercloud.ems.service.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.econ.powercloud.ems.dal.entity.EmsGridRecordNode;
import com.econ.powercloud.ems.dal.mapper.EmsGridRecordNodeMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * EmsGridRecordNodeDAO
 * @author jwc
 * @since 2022/08/26
 */
@Repository
public class EmsGridRecordNodeDAO extends ServiceImpl<EmsGridRecordNodeMapper, EmsGridRecordNode> {

    private final String LIMIT_ONE = "limit 1";

    public List<EmsGridRecordNode> selectByRecordGroupId(Long recordGroupId) {
        LambdaQueryWrapper<EmsGridRecordNode> wrapper = Wrappers.<EmsGridRecordNode>lambdaQuery()
                .eq(EmsGridRecordNode::getRecordGroupId, recordGroupId);
        return this.baseMapper.selectList(wrapper);
    }

    public List<EmsGridRecordNode> selectByRecordGroupIds(List<Long> recordGroupIds) {
        LambdaQueryWrapper<EmsGridRecordNode> wrapper = Wrappers.<EmsGridRecordNode>lambdaQuery()
                .in(EmsGridRecordNode::getRecordGroupId, recordGroupIds);
        return this.baseMapper.selectList(wrapper);
    }

    /**
     * 查询前置节点的节点记录
     * @param recordGroupId 组合记录的id
     * @param processNodeIdList 节点id集合
     * @return 节点记录集合
     */
    public List<EmsGridRecordNode> selectByRecordGroupIdAndProcessNodeId(Long recordGroupId, List<Long> processNodeIdList) {
        LambdaQueryWrapper<EmsGridRecordNode> wrapper = Wrappers.<EmsGridRecordNode>lambdaQuery()
                .eq(EmsGridRecordNode::getRecordGroupId, recordGroupId)
                .in(EmsGridRecordNode::getProcessNodeId, processNodeIdList);
        return this.baseMapper.selectList(wrapper);
    }

    /**
     * 获取某组合下最新的节点记录
     * @param recordGroupId 组合记录id
     * @return
     */
    public EmsGridRecordNode selectLatestByGroupId(Long recordGroupId) {
        LambdaQueryWrapper<EmsGridRecordNode> wrapper = Wrappers.<EmsGridRecordNode>lambdaQuery()
                .eq(EmsGridRecordNode::getRecordGroupId, recordGroupId).orderByDesc(EmsGridRecordNode::getId).last(LIMIT_ONE);
        return this.baseMapper.selectOne(wrapper);
    }

    public List<EmsGridRecordNode> selectByRecordIdAndProcessNodeIds(Long recordId, List<Long> processNodeIdList) {
        LambdaQueryWrapper<EmsGridRecordNode> wrapper = Wrappers.<EmsGridRecordNode>lambdaQuery()
                .eq(EmsGridRecordNode::getRecordId, recordId)
                .in(EmsGridRecordNode::getProcessNodeId, processNodeIdList);
        return this.baseMapper.selectList(wrapper);
    }
}
